package com.by_man.presenter;

/*
** 登录页面
 */
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.by_man.presenter.main_page.MainActivity;
import com.by_man.presenter.menu_activity.Setting_self;
import com.by_man.repository.BackgroundService;
import com.by_man.repository.UserInfos;

import org.json.JSONObject;




public class LoginActivity extends AppCompatActivity {

    private RequestQueue rQueue;
    private Handler handler;
    private final static int INVALID_INPUT = 0x1;
    private final static int SUCCESS_MAIN = 0x2;
    private final static int SUCCESS_SELF = 0x3;
    private final static int FAIL = 0x4;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 这句一定要放在setContentView前面,在这里无效
        //requestWindowFeature(Window.FEATURE_NO_TITLE);                          // 无标题
        //getSupportActionBar().hide();                                             // 使用此函数可以达到隐藏标题
        setContentView(R.layout.activity_login);
        initUI();
        // 通用的Activity初始方法。
        rQueue = SharedApplication.getrQueue(getApplication());
        rQueue.start();
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    case INVALID_INPUT:
                        SharedApplication.showToast(LoginActivity.this, "用户名或密码错误！");
                        break;
                    case SUCCESS_MAIN:
                        // 初始化环境，开启服务
                        startService(new Intent(LoginActivity.this, BackgroundService.class));
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                        break;
                    case SUCCESS_SELF:
                        // 初始化环境，开启服务
                        startService(new Intent(LoginActivity.this, BackgroundService.class));
                        Intent intent_self = new Intent(LoginActivity.this, Setting_self.class);
                        intent_self.putExtra("isFirst", true);
                        intent_self.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent_self);
                        break;
                    case FAIL:
                        SharedApplication.showToast(LoginActivity.this, "网络出错！");
                        break;
                }
            }
        };
        // 加上这句设置为全屏 不加则只隐藏title
        //acache=ACache.get(this);   //创建ACache组件
        //final Activity activityclass = this;
        //((SharedApplication)getApplication()).addActivity(this);
        // ??
        // 设置透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //PushManager.startWork(getApplicationContext(), PushConstants.LOGIN_TYPE_API_KEY, "APc8PRmZxh7pWMIPufKrdiVn");
        // ??
    }

    // 做UI方面的相关初始化
    public void initUI() {
        Button land = (Button) findViewById(R.id.landing);
        Button forget = (Button) findViewById(R.id.forget);
        TextView userIcon = (TextView) findViewById(R.id.user_icon);
        TextView passwordIcon = (TextView) findViewById(R.id.password_icon);
        Typeface iconfont = Typeface.createFromAsset(getAssets(), "icon/iconfont.ttf");
        userIcon.setTypeface(iconfont);
        passwordIcon.setTypeface(iconfont);
        final EditText usernameView = (EditText) findViewById(R.id.input_user_name);
        final EditText passwordView = (EditText) findViewById(R.id.input_password);

        // 设定相关事件监听
        // 点击后产生提示对话框，用户确定后将跳转拨号界面
        forget.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(LoginActivity.this).setTitle("系统提示")
                        .setMessage("请联系账号管理员：")
                        .setPositiveButton("010-68410099", new DialogInterface.OnClickListener() {//添加确定按钮
                            @Override
                            public void onClick(DialogInterface dialog, int which) {//确定按钮的响应事件
                                Intent intent = new Intent(Intent.ACTION_DIAL);
                                intent.setData(Uri.parse("tel:68410099"));
                                startActivity(intent);
                            }
                        }).show();//在按键响应事件中显示此对话框
            }
        });

        // 登录按钮注册监听
        land.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // 取出用户输入信息
                String username = usernameView.getText().toString().trim();
                String password = passwordView.getText().toString().trim();
                // 判断合法性
                if (0 == username.length() || 0 == password.length())
                    SharedApplication.showToast(LoginActivity.this, "用户名或密码为空，请重新填写！");
                else {
                    // 进行网络验证
                    String url = getResources().getString(R.string.login_address) +
                            "?username=" + username + "&password=" + SharedApplication.MD5("$20160608$" + password, 32);
                    // 向队列中添加网络请求
                    StringRequest stringRequest = new StringRequest(url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    if (response.equalsIgnoreCase("nopermission")) {
                                        Message msg = handler.obtainMessage();
                                        msg.what = INVALID_INPUT;
                                        msg.sendToTarget();
                                    }
                                    else {
                                        try {
                                            JSONObject json = new JSONObject(response);
                                            // 存储获取到的token
                                            UserInfos.token = (String)json.get("token");
                                            /***************************************************************
                                             *
                                             ***************************************************************/
                                            boolean isFull = json.getBoolean("isFull");
                                            if (isFull) {    // 跳转MainActivity
                                                Message msg = handler.obtainMessage();
                                                msg.what = SUCCESS_MAIN;
                                                msg.sendToTarget();
                                            } else {         // 跳转完善信息页面
                                                Message msg = handler.obtainMessage();
                                                msg.what = SUCCESS_SELF;
                                                msg.sendToTarget();
                                            }
                                        } catch (Exception e) {
                                            Log.i("Exception", e.toString());
                                        }
                                    }
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError volleyError) {
                                    Log.e("LoginActivity2", volleyError.getMessage(), volleyError);
                                    Message msg = handler.obtainMessage();
                                    msg.what = FAIL;
                                    msg.sendToTarget();
                                }
                            });
                    rQueue.add(stringRequest);
                }
            }
        });

    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK) { //监控/拦截/屏蔽返回键
            showTips();
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showTips() {
        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).setTitle("提醒")
                .setMessage("是否退出程序")
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dialog, int which) {
                        finishAffinity();
                    }

                }).setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                return;
                            }
                        }).create(); // 创建对话框
        alertDialog.show(); // 显示对话框
    }

    @Override
    protected void onDestroy(){
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }
}
